package com.yingjie.commonsecurity.filter;

import com.alibaba.fastjson.JSONObject;


import com.yingjie.commonbase.bo.UserAuthBo;
import com.yingjie.commonbase.bo.UserInfoInTokenBO;
import com.yingjie.commonbase.commons.Constents;
import com.yingjie.commonbase.commons.JWTUtils;
import com.yingjie.commonbase.commons.ReturnCodeMsg;
import com.yingjie.commonbase.commons.ReturnObject;


import com.yingjie.commonsecurity.AuthUserContext;
import com.yingjie.yingjieapi.openFeign.AuthFeign;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class AuthFilter implements Filter {

    //路由地址匹配器，用于检查是否包含我们设置的不需要过滤的路由
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Resource
    private AuthFeign authFeign;
    /**
     *
     * @param urls 不需要过滤的路由
     * @param requestUrl 本次请求的路由地址
     * @return
     */
    public boolean check(String[] urls, String requestUrl) {
        for (String url : urls) {
            if (PATH_MATCHER.match(url, requestUrl)) {
                return true;
            }
        }
        return false;
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 获取请求路径
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;
        String url=request.getRequestURI().toString();
        //免登录 放行的接口
        String[] strings = Constents.noLoginPaths;
        if(check(strings,url)){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }

        //接口拦截
        String token = request.getHeader("token");
        Claims claims = null;
        try{
            claims = JWTUtils.parseJwt(token);
        } catch (Exception e) {
            e.printStackTrace();
//            log.info("解析令牌失败，返回未登录信息");
            // 自定义返回的 ：请登录
            ReturnObject re = ReturnObject.ERROR(ReturnCodeMsg.NO_LOGIN);
            String notLogin = JSONObject.toJSONString(re);
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/json;charset=UTF-8");
            response.getWriter().write(notLogin);
            return;
        }
        System.out.println("通过token验证");
        Integer userId = (Integer) claims.get("userId");
        //认证服务校验userid
        ReturnObject<UserAuthBo> res = authFeign.userAuth(userId);
        if(res.getCode()== ReturnCodeMsg.NO_DISABLE.value()){
            //用户被禁用
            ReturnObject re = ReturnObject.ERROR(ReturnCodeMsg.NO_DISABLE);
            String notLogin = JSONObject.toJSONString(re);
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/json;charset=UTF-8");
            response.getWriter().write(notLogin);
            return;
        }

        UserInfoInTokenBO userInfoInTokenBO = new UserInfoInTokenBO();
        userInfoInTokenBO.setUserId(userId);
        //userId存到当线程方便获取
        AuthUserContext.set(userInfoInTokenBO);
        filterChain.doFilter(servletRequest,servletResponse);
        return;
    }
}